#include "mydatabase.h"
#include <QSqlQuery>
#include <QVariant>
#include <QSqlError>
#include <QDateTime>

MyDatabase::MyDatabase(QObject *parent): QObject(parent)
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName("/opt/ForkliftScale/mydatabase.db");
    m_db.open();
    //
    //m_clientID=QString("33D49E7E");
}
//QSqlDatabase MyDatabase::initialDatabase()
//{
//    // 创建 QSqlDatabase 对象并连接到 SQLite 数据库
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("mydatabase.db");
//    return db;
//}
//void MyDatabase::closeDatabase(QSqlDatabase db)
//{
//    db.close();
//}
bool MyDatabase::existTable(QSqlDatabase db, QString tableName)
{
    bool result = false;
    QSqlQuery query0(db);
    bool tableExists0 = query0.exec(QString("select name FROM sqlite_master WHERE type='table' AND name='%1';").arg(tableName));  
    if (!tableExists0 || !query0.next())
    {
        result = false;
    }
    else
    {
        result = true;
    }
    query0.finish();
    return result;
}
bool MyDatabase::existColumn(QSqlDatabase db, QString tableName, QString columnName)
{
    QSqlQuery query(db);
    QString sql = QString("PRAGMA table_info(%1);").arg(tableName);
    bool result = query.exec(sql);
    if (!result) {
        query.finish();
        return false;
    }    
    bool columnExists = false;
    while (query.next()) {
        QString name = query.value(1).toString();
        if (name == columnName) {
            columnExists = true;
            break;
        }
    }    
    query.finish();
    return columnExists;
}
void MyDatabase::openDB()
{
    //m_db.open();
}

void MyDatabase::closeDB()
{
    m_db.close();
}
bool MyDatabase::checkOrCreateDatabase()
{
    // 执行 SQL 查询，判断数据库中是否存在某个表
    QSqlQuery query0(m_db);
    // 如果查询失败或者结果集中没有数据，则表示表不存在，需要创建
    if (!existTable(m_db, "weightTable")) {
        // 创建表
        bool tableCreated = query0.exec("CREATE TABLE weightTable (id  TEXT DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-a' || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6))))"
                                        " PRIMARY KEY, weight NUMERIC, weightUnit varchar(64), createdTime TimeStamp NOT NULL DEFAULT CURRENT_TIMESTAMP, isSend INTEGER DEFAULT 0, lon NUMERIC, lon_o NUMERIC, lonDir varchar(64), lat NUMERIC, lat_o NUMERIC, latDir varchar(64), height NUMERIC, heightUnit  varchar(64), truckNo varchar(1000), angle NUMERIC, mode INTEGER DEFAULT -1, scheduled INTEGER DEFAULT 1);");

        if (!tableCreated) {
            // 创建表失败，返回 false
            query0.finish();
            return false;
        }
    }
    query0.finish();
    // 返回 true，表示数据库存在并且已创建
    return true;
}

//QList<weightdata*> MyDatabase::getWeightData()
//{
//    QList<weightdata*> list;
//    QSqlDatabase db = initialDatabase();
//    if(!db.open())
//    {
//        return list;
//    }

//    if(existTable(db,"weightTable"))
//    {
//        QSqlQuery query(db);
//        query.exec("SELECT id, weight, createdTime FROM weightTable;");
//        while(query.next())
//        {
//            int id = query.value(0).toInt();
//            float weight = query.value(1).toFloat();
//            QDateTime time = query.value(2).toDateTime();

//            weightdata data = weightdata(id,weight,time);
//            list.push_back(&data);
//        }
//    }
//    else
//    {
//        return list;
//    }
//    // 关闭数据库连接
//    // 关闭数据库连接
//    closeDatabase(db);

//    // 返回 true，表示数据库存在并且已创建
//    m_weightdata =list;
//    return list;
//}
//QList<weightdata*> MyDatabase::weightData() const
//{
//    return m_weightdata;
//}
